package logic

import (
	"context"
	"fmt"
	"yuni/model/mysql"

	"yuni/yunirpc/internal/svc"
	"yuni/yunirpc/yunirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectAddLogic {
	return &CollectAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CollectAddLogic) CollectAdd(in *yunirpc.CollectAddRequest) (*yunirpc.CollectAddResponse, error) {
	// todo: add your logic here and delete this line
	begin := mysql.Db.Debug().Begin()
	var user mysql.User
	begin.Debug().Where("id=?", in.UserId).Find(&user)
	if user.ID == 0 {
		begin.Rollback()
		return nil, fmt.Errorf("用户不存在")
	}
	var Product mysql.Product
	begin.Debug().Where("id=?", in.ProductId).Find(&Product)
	if Product.ID == 0 {
		begin.Rollback()
		return nil, fmt.Errorf("商品不存在")
	}
	collect := mysql.Collect{
		UserId:    in.UserId,
		ProductId: in.ProductId,
	}
	begin.Debug().Create(&collect)
	begin.Commit()

	return &yunirpc.CollectAddResponse{
		CollectId: int64(collect.ID),
	}, nil
}
